package cn.jlkj.tomcat;

import javax.servlet.ServletException;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

public class SocketProcessor implements Runnable{
    private Socket socket;

    public SocketProcessor(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        processSocket(socket);
    }

    private void processSocket(Socket socket) {
        //处理Socket连接  读数据  写数据
        try {
            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            inputStream.read(bytes);
            //解析字节流 遇到空格就退出
            int pos=0;
            int begin=0,end=0;
            for (;pos<bytes.length;pos++,end++){
                if (bytes[pos]==' ')break;
            }
            //组合空格之前的字节流，转换成字符串就是请求方法
            StringBuilder method = new StringBuilder();
            for (;begin<end;begin++){
                method.append((char)bytes[begin]);
            }

            //解析url
            pos++;
            begin++;
            end++;
            for (;pos<bytes.length;pos++,end++){
                if (bytes[pos]==' ')break;
            }
            StringBuilder url = new StringBuilder();
            for (;begin<end;begin++){
                url.append((char)bytes[begin]);
            }

            //解析协议版本
            pos++;
            begin++;
            end++;
            for (;pos<bytes.length;pos++,end++){
                if (bytes[pos]=='\r')break;
            }
            StringBuilder protocol = new StringBuilder();
            for (;begin<end;begin++){
                protocol.append((char)bytes[begin]);
            }

            Request request = new Request(method.toString(), url.toString(), protocol.toString(),socket);
            Response response = new Response(request);
            //匹配SeverLet、doGet
            Servlet servlet = new Servlet();
            servlet.service(request,response);

            //发送相应
            response.complete();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        }

    }
}
